import { DownOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Divider, Dropdown, Menu, message, Icon, Drawer, Switch } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule, queryItemRule, addItemRule, removeItemRule, updateItemRule } from './service';
import moment from 'moment';
import { bdExec } from '@/helpers/RequestHelper';
import styles from './styles.less';
import * as tsxHelper from '@/helpers/TsxHelper';

interface TableListProps extends FormComponentProps {}

/**
 * 添加节点
 */
const handleAdd = async (fields: FormValueType) => {
  return bdExec({fn: addRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

const handleAddItem = async (fields: FormValueType) => {
  return bdExec({fn: addItemRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

/**
 * 更新节点
 */
const handleUpdate = async (fields: FormValueType) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

const handleUpdateItem = async (fields: FormValueType) => {
  return bdExec({fn: updateItemRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows.map(row => row.id).toString();
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！',hasLoading: false});
};

const handleRemoveSingle = async (ids: string) => {
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！',hasLoading: false});
};

const handleRemoveItemSingle = async (ids: string) => {
  return bdExec({fn: removeItemRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！', hasLoading: false});
};


const DictionaryList: React.FC<TableListProps> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [itemModalVisible, setItemModalVisible] = useState<boolean>(false);
  const [itemUpdataModalVisible, setItemUpdataModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [dictId, setDictId] = useState<number>(0);
  const [parentDictName,setParentDictName] = useState<String>('');
  const actionRef = useRef<ActionType>();
  const itemActionRef = useRef<ActionType>();
  const [stateData, setStateData] = useState<any>({data: {}});

  const itemColumns: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '标识',
      dataIndex: 'nickname',
    },
    {
      title: '数据值',
      dataIndex: 'item_value',
    },
    {
      title: '对比值',
      dataIndex: 'dict_item_value',
    },
    {
      title: '描述',
      dataIndex: 'remark',
    },
    {
      title: '是否启用',
      dataIndex: '',
      render: (_, record) => (
        <Switch checked={record.is_enable} onChange={async () => {
          let s = await handleUpdateItem({id: record.id, is_enable: (!record.is_enable).toString()});
          s && itemActionRef.current?.reload();
        }} />
      )
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: 'right',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(false);
              setItemUpdataModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              tsxHelper.showDeleteConfirm(
                'danger',
                handleRemoveItemSingle,
                record.id.toString(),
                () => {
                  itemActionRef.current?.reload()
                }
              )
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '字典名称',
      dataIndex: 'name',
    },
    {
      title: '字典编号',
      dataIndex: 'nickname',
    },
    {
      title: '描述',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      sorter: true,
      hideInSearch: true,
      render: (val:any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            <Icon type='edit' style={{marginRight: 6}} />编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setDrawerVisible(true);
              setDictId(record.id);
              setParentDictName(record.name||'');
            }}
          >
            <Icon type='setting'style={{marginRight: 6}}/>字典配置
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              tsxHelper.showDeleteConfirm(
                'danger',
                handleRemoveSingle,
                record.id.toString(),
                () => {
                  actionRef.current?.reload()
                }
              )
              // let status = await handleRemoveSingle(record.id.toString());
              // status && actionRef.current?.reload()
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const getListData = (params:any) => {
    return queryRule(params).then((res:any) => {
      if(res.code === 0){
        setStateData(res)
        return res.data.listData;
      }else{
        message.error(res.msg);
      }
    })
  }

  const fetDictItemListById = (params:any) => {
    return queryItemRule(params).then((res:any) => {
      if(res.code === 0){
        return res.data.listData;
      }else{
        message.error(res.msg);
      }
    })
  }

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={'plus'} type="primary" onClick={() => {
            handleModalVisible(true);
            
          }}>
            新建
          </Button>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      tsxHelper.showDeleteConfirm(
                        'danger',
                        handleRemove,
                        selectedRows,
                        () => {
                          setRowKeys([]);
                          action.reload();
                        }
                      )
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        tableAlertRender={(selectedRowKeys, selectedRows) => (
          <div>
            已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
          </div>
        )}
        request={params => getListData(params)}
        columns={columns}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            setRowKeys(selectedRowKeys);
          },
          selectedRowKeys: rowKeys,
        }}
      />
      <CreateForm
        onSubmit={ value => {
          return new Promise((resolve, reject) => {
            let s = itemModalVisible ? handleAddItem(value) : handleAdd(value);
            resolve(s);
          }).then( status => {
            if(status){
              itemModalVisible ? setItemModalVisible(false) : handleModalVisible(false);
              itemModalVisible ? itemActionRef.current?.reload() : actionRef.current?.reload();
            }
            return status;
          })
        }}
        onCancel={() => {
          setItemModalVisible(false);
          handleModalVisible(false);
        }}
        modalVisible={createModalVisible}
        itemModalVisible={itemModalVisible}
        otherValues={{
          common: stateData.data.common || {},
          dictId,
        }}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = itemUpdataModalVisible ? 
            await handleUpdateItem(value) :
            await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setItemUpdataModalVisible(false);
              setStepFormValues({});
              itemUpdataModalVisible ? itemActionRef.current?.reload() : actionRef.current?.reload();
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setItemUpdataModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          itemUpdataModalVisible={itemUpdataModalVisible}
          values={stepFormValues}
        />
      ) : null}

      {
        <Drawer
          // title={`字典: ${parentDictName}`}
          placement="right"
          width="39%"
          closable={false}
          onClose={() => {
            setDrawerVisible(false)
            setItemModalVisible(false)
          }}
          visible={drawerVisible}
          className={styles.dbDrawer}
        >
          <ProTable<any>
            headerTitle={`字典:${parentDictName}`}
            actionRef={itemActionRef}
            rowKey="key"
            search={false}
            // pagination={false}
            toolBarRender={(action, { selectedRows }) => [
              <Button icon={'plus'} type="primary" 
                onClick={() => {
                  setItemModalVisible(true)
                }}
              >
                新建
              </Button>
            ]}
            request={(params) => fetDictItemListById(params)}
            params={{
              dict_id: dictId
            }}
            columns={itemColumns}
          />
        </Drawer>
      }
    </PageHeaderWrapper>
  );
};

export default Form.create<TableListProps>()(DictionaryList);
